﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Linq;
using System.Linq;
using System.Text;

namespace Jiubang.Authentications.Loggers
{
    /// <summary>
    /// 数据库日志写入接口的默认实现
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class DbLogger<T>:ILogger where T :class,IDbLoggerInfo,new()
    {
        private readonly string conn;

        /// <param name="connectionName">在connections节点中的数据库连接名称</param>
        public DbLogger(string connectionName)
        {
            conn = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
        }

        /// <summary>
        /// 将消息以同步方式写入数据库。
        /// 考虑初期用户并发有限，暂未添加高级特性。
        /// 本接口应由<see cref="Authentication"/>类调用。
        /// </summary>
        /// <param name="session">当前用户会话信息</param>
        /// <param name="path">当前用户请求的路径</param>
        /// <param name="action">用户请求动作</param>
        /// <param name="detail">动作参数</param>
        public void Log(UserSession session, string path, string action, string detail) {
            var logInfo = new T { UserID = session.UserID, Path = path, Action = action, Detail = detail };
            using (var ctx=new DataContext(conn)) {
                ctx.GetTable<T>().InsertOnSubmit(logInfo);
                ctx.SubmitChanges();
            }
        }
    }
}
